package org.ii.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Element;
import org.ii.dataprovider.dapper.Dapp;
import org.ii.dataprovider.dapper.brreg.SearchBrregRegisterByCompanyNameDapperService;
import org.ii.domain.company.BrregCompany;


public class SearchBrregRegisterByCompanyNameDapperServiceImpl implements SearchBrregRegisterByCompanyNameDapperService {
	
	protected Dapp dapp;	
	protected String DAPP_NAME = "ii42org_brreg_namesearch";
	protected String DAPP_ROOT_ELEMENT = "org";
	protected String DAPP_NAME_ELEMENT = "orgname";
	protected String DAPP_ORGNUMBER_ELEMENT = "orgnumber";
	
	/* (non-Javadoc)
	 * @see org.ii.dataprovider.dapper.brreg.SearchBrregRegisterByCompanyNameService#searchBrregRegisterByCompanyName(java.lang.String)
	 */
	@Override 
	public List<BrregCompany> searchBrregRegisterByCompanyName(String companyName) throws Exception {
		List<BrregCompany> companies = new ArrayList<BrregCompany>();
		dapp = new Dapp(DAPP_NAME, new String[]{companyName});
		companies = getSetOfBrregCompaniesFromDappResult(dapp);
		return companies;
	}

	@SuppressWarnings("unchecked")
	private List<BrregCompany> getSetOfBrregCompaniesFromDappResult(Dapp searchBrregByCompanyNameDappResults) throws Exception {
		List<BrregCompany> companies = new ArrayList<BrregCompany>();
		BrregCompany newCompany;
		Iterator<Element> searchResultsItr = dapp.getDOM().getRootElement().elementIterator(DAPP_ROOT_ELEMENT);
		while (searchResultsItr.hasNext()){
			newCompany = new BrregCompany();
			Element searchResults = searchResultsItr.next();
			newCompany.setName(searchResults.elementText(CompanyDapperFields.ORGNAME.dapperFieldName));
			newCompany.setOrgNr(searchResults.elementText(CompanyDapperFields.ORGNR.dapperFieldName));
			Iterator<Element> orgNameItr = searchResults.elementIterator(CompanyDapperFields.ORGNAME.dapperFieldName);
			while (orgNameItr.hasNext()){
				Element org = orgNameItr.next();
				newCompany.setInfoUrl(org.attributeValue(CompanyDapperFields.ORGURL.dapperFieldName));
			}
			companies.add(newCompany);
		}
		return companies;
	}
	
}
